package com.android.bonn.fast.widget.view;

import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * author huangyunlin@snqu.com
 * date 2018/12/14
 * description
 */
public abstract class OnRecyclerViewScrollChangeListener extends RecyclerView.OnScrollListener {

    private int color = -1;
    private static final int HIDE_THRESHOLD = 10;
    private int scrolledDistance = 0;
    private boolean controlsVisible = true;
    private View headerView;

    public OnRecyclerViewScrollChangeListener(View headerView) {
        this.headerView = headerView;
    }

    public OnRecyclerViewScrollChangeListener(int color, View headerView) {
        this.headerView = headerView;
        this.color = color;
    }

    public OnRecyclerViewScrollChangeListener(int color) {
        this.color = color;
    }

    @Override
    public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
    }

    @Override
    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        int temp = color;
        if (color != -1) {
            if (dy < 256) {
                int alpha = (dy << 24) | (-1 >>> 8);
                temp = color & (alpha);
            }
        }


        onChange(recyclerView, temp, dx, dy);

        if (headerView != null) {
            int firstVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
            if (firstVisibleItem >= 1) {
                if (scrolledDistance > HIDE_THRESHOLD && controlsVisible) {
                    // 隐藏toolbar
                    hideViews();
                    controlsVisible = false;
                    scrolledDistance = 0;
                } else if (scrolledDistance < -HIDE_THRESHOLD && !controlsVisible) {
                    // 显示toolbar
                    showViews();
                    controlsVisible = true;
                    scrolledDistance = 0;
                }
                if ((controlsVisible && dy > 0) || (!controlsVisible && dy < 0)) {
                    scrolledDistance += dy;
                }
            }
        }


    }

    public abstract void onChange(RecyclerView recyclerView, int color, int dx, int dy);

    private void hideViews() {
        headerView.animate().translationY(-headerView.getHeight() * 2).setInterpolator(new AccelerateInterpolator(2));
    }

    private void showViews() {
        headerView.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2));
    }

}
